package com.wisewin.circle.util.wechat.xcx.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileUtil {

    /**
     * 网络地址转为Input
     *
     * @param httpUrl
     * @return
     */
    public static InputStream urlToInputStream(String httpUrl) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(httpUrl).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            System.out.println("获取网络图片出现异常，图片路径为：" + httpUrl);
            e.printStackTrace();
        }
        return null;
    }


    /**
     * @param httpUrl 网络地址
     * @param suffix  文件后缀 如 .png
     * @return
     */
    public static File urlToFile(String httpUrl, String suffix) {
        File file = null;

        URL urlfile;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            file = File.createTempFile("http-item", suffix);
            //下载
            urlfile = new URL(httpUrl);
            inputStream = urlfile.openStream();
            outputStream = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }
}
